// components/dialog/dialog.js
Component({
  options: {
    styleIsolation: "isolated"
  },
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      type: String,
      value: "标题"
    },
    cancelButtonText: {
      type: String,
      value: "取消"
    },
    confirmButtonText: {
      type: String,
      value: "确定"
    },
    show: {
      type: Boolean,
      value: false,
    },
    confirmCallback: null,
    cancelCallback: null,
  },

  /**
   * 组件的初始数据
   */
  data: {
    windowWidth: 0,
    windowHeight: 0,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onConfirm() {
      if (this.properties.confirmCallback) {
          this.properties.confirmCallback();
      }
      this.setData({ show: false });
    },
    onCancel() {
      if (this.properties.cancelCallback) {
          this.properties.cancelCallback();
      }
      this.setData({ show: false });
    },
  },

  ready: function() {
    var _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
        });
      }
    });
  },
})

const defaultOptions = {
  show: false,
  selector: "#dialog",
  confirmButtonText: "确认",
  cancelButtonText: "取消",
  confirmCallback: null,
  cancelCallback: null,
};
let currentOptions = Object.assign({}, defaultOptions);
function getContext() {
  const pages = getCurrentPages();
  return pages[pages.length - 1];
}
const Dialog = (options) => {
  options = Object.assign(Object.assign({}, currentOptions), options);
  const context = options.context || getContext();
  const dialog = context.selectComponent(options.selector);
  delete options.context;
  delete options.selector;
  if (dialog) {
    dialog.setData(options);
    wx.nextTick(() => {
      dialog.setData({ show: true });
    });
  }
};
Dialog.confirm = (options) => Dialog(Object.assign({ showCancelButton: true }, options));
export default Dialog;
